package com.tcpengine.net;

import java.net.URI;
import java.util.Enumeration;

import javax.swing.JTextArea;

import com.tcpengine.client.LogView;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

// websocket客户端
public class WsClient {
	
	private LogView m_logView;
	Channel m_ch = null;
	
	
	public WsClient(LogView logView) {
		m_logView = logView;
	}
	
	public void wsConnect(String strUrl) throws Exception {
		m_logView.println("开始连接websocket服务器 " + strUrl);
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap boot = new Bootstrap();
        boot.option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true)
                .group(group)
                .handler(new LoggingHandler(LogLevel.INFO))
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast("http-codec",new HttpClientCodec());
                        pipeline.addLast("aggregator",new HttpObjectAggregator(1024*1024*10));
                        pipeline.addLast("hookedHandler", new WsHandler(m_logView));
                    }
                });
        URI websocketURI = new URI(strUrl);
        HttpHeaders httpHeaders = new DefaultHttpHeaders();
        WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(websocketURI, WebSocketVersion.V13, (String) null, true, httpHeaders);
        m_ch = boot.connect(websocketURI.getHost(), websocketURI.getPort()).sync().channel();
        WsHandler handler = (WsHandler) m_ch.pipeline().get("hookedHandler");
        handler.setHandshaker(handshaker);
        handshaker.handshake(m_ch);
        handler.handshakeFuture().sync();
        
        m_logView.println("webscoket 连接成功");
        
        // sendMessage(channel);
	}
	
	
	public void sendMessage(Msg msg) {
		BinaryWebSocketFrame binaryFrame = new BinaryWebSocketFrame(Encoder.encode(msg));
		m_ch.writeAndFlush(binaryFrame).addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if (channelFuture.isSuccess()) {
                    m_logView.println("websocket发送消息成功");
                } else {
                	m_logView.println("websocket消息发送失败 " + channelFuture.cause().getMessage());
                }
            }
        });
		
//		 // String putMessage="你好，我是客户端";
//		String putMessage="abc";
//	        TextWebSocketFrame frame = new TextWebSocketFrame(putMessage);
//	        m_ch.writeAndFlush(frame).addListener(new ChannelFutureListener() {
//	            public void operationComplete(ChannelFuture channelFuture) throws Exception {
//	                if (channelFuture.isSuccess()) {
//	                    System.out.println("消息发送成功，发送的消息是："+putMessage);
//	                } else {
//	                    System.out.println("消息发送失败 " + channelFuture.cause().getMessage());
//	                }
//	            }
//	        });
		 
	}

    public static void sendMessage(Channel channel){
        //发送的内容，是一个文本格式的内容
        String putMessage="你好，我是客户端";
        TextWebSocketFrame frame = new TextWebSocketFrame(putMessage);
        channel.writeAndFlush(frame).addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if (channelFuture.isSuccess()) {
                    System.out.println("消息发送成功，发送的消息是："+putMessage);
                } else {
                    System.out.println("消息发送失败 " + channelFuture.cause().getMessage());
                }
            }
        });
    }
	
}
